#!/usr/bin/env python3
"""
准备PeiYangGuide API测试数据
此脚本将创建基本的测试数据，包括活动、公告和表单
"""

import sys
import os
import time
from datetime import datetime, timedelta
import json
import asyncio
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import text
import pytest

# 添加项目根目录到路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.database import async_session
# from app.models.admin import Admin
# from app.models.announcement import Activity, Announcement, ActivityCampus
# from app.models.form import Form, FormItem, form_form_item_list
# from app.core.security import get_password_hash

async def test_database_connection():
    """测试数据库连接"""
    try:
        async with async_session() as session:
            # 使用 text() 函数包装 SQL 查询
            result = await session.execute(text("SELECT 1"))
            await session.commit()  # 添加显式提交
            print("✅ 数据库连接测试成功！")
            return True
    except Exception as e:
        print(f"❌ 数据库连接测试失败: {e}")
        return False

async def prepare_test_data():
    """准备测试数据"""
    # 首先测试数据库连接
    if not await test_database_connection():
        print("由于数据库连接失败，终止测试数据准备")
        return
        
    async with async_session() as session:
        try:
            print("开始准备测试数据...")

            # 1. 创建测试管理员（如果不存在）
            test_admin = await session.get(Admin, 2)
            if not test_admin:
                test_admin = Admin(
                    id=2,  # 显式设置ID为2，因为admin已经是1
                    username="test_admin",
                    password=get_password_hash("test_password"),
                    display_name="测试管理员",
                    avatar="https://example.com/avatar.png",
                    permission=2,
                )
                session.add(test_admin)
                await session.commit()
                await session.refresh(test_admin)
                print("创建测试管理员成功")
            else:
                print("测试管理员已存在")

            # 跳过测试公告创建，因为announcement表结构与模型不匹配
            # 2. 创建测试公告
            # test_announcement = await session.get(Announcement, 1)
            # if not test_announcement:
            #     test_announcement = Announcement(
            #         name="测试公告",
            #         published_time=datetime.now(),
            #         campus=json.dumps([0, 1]),  # 校区列表
            #         type=0,
            #         poster="https://example.com/poster.jpg",
            #         publisher_id=test_admin.id,
            #         content="<p>这是一个测试公告内容</p>"
            #     )
            #     session.add(test_announcement)
            #     await session.commit()
            #     await session.refresh(test_announcement)
            #     print("创建测试公告成功")
            # else:
            #     print("测试公告已存在")

            # 3. 创建测试表单
            test_form = await session.get(Form, 1)
            if not test_form:
                test_form = Form(id=1, created_user_id=test_admin.id)  # 显式设置ID为1
                session.add(test_form)
                await session.commit()
                await session.refresh(test_form)
                print("创建测试表单成功")
            else:
                print("测试表单已存在")

            # 4. 创建测试表单项
            test_form_item1 = await session.get(FormItem, 1)
            test_form_item2 = await session.get(FormItem, 2)

            if not test_form_item1:
                test_form_item1 = FormItem(id=1, label="姓名")  # 显式设置ID为1
                session.add(test_form_item1)
                await session.commit()
                await session.refresh(test_form_item1)
                print("创建测试表单项1成功")
            else:
                print("测试表单项1已存在")

            if not test_form_item2:
                test_form_item2 = FormItem(id=2, label="性别")  # 显式设置ID为2
                session.add(test_form_item2)
                await session.commit()
                await session.refresh(test_form_item2)
                print("创建测试表单项2成功")
            else:
                print("测试表单项2已存在")

            # 关联表单和表单项
            try:
                await session.execute(
                    form_form_item_list.insert().values(
                        form_id=test_form.id, form_item_list_id=test_form_item1.id
                    )
                )
                await session.execute(
                    form_form_item_list.insert().values(
                        form_id=test_form.id, form_item_list_id=test_form_item2.id
                    )
                )
                await session.commit()
                print("关联表单和表单项成功")
            except Exception as e:
                print(f"关联表单和表单项时出错（可能已存在关联）: {e}")

            # 5. 创建测试活动
            test_activity = await session.get(Activity, 1)
            if not test_activity:
                test_activity = Activity(
                    id=1,  # 显式设置ID为1
                    name="测试活动",
                    activity_time=datetime.now() + timedelta(days=1),
                    submission_deadline=datetime.now() + timedelta(hours=12),
                    location="测试位置",
                    additional_conditions="无特殊要求",
                    count_limit="100",
                    type=0,
                    poster="https://example.com/activity_poster.jpg",
                    publisher=test_admin.id,
                    content="<p>这是一个测试活动内容</p>",
                    form_id=test_form.id,
                )
                session.add(test_activity)
                await session.commit()
                await session.refresh(test_activity)
                print("创建测试活动成功")

                # 创建活动校区关联
                test_activity_campus = ActivityCampus(
                    activity_id=test_activity.id, campus=0
                )
                session.add(test_activity_campus)
                await session.commit()
                print("创建活动校区关联成功")
            else:
                print("测试活动已存在")

            print("测试数据准备完成！")

        except Exception as e:
            await session.rollback()
            print(f"准备测试数据时出错: {e}")

async def main():
    """主函数"""
    await prepare_test_data()

@pytest.mark.asyncio
async def test_database():
    """Pytest 异步测试函数"""
    try:
        result = await test_database_connection()
        assert result == True
    finally:
        # 确保清理所有挂起的连接
        await asyncio.sleep(0.1)

if __name__ == "__main__":
    try:
        asyncio.run(test_database())
    except AssertionError:
        print("测试失败：数据库连接测试未通过")
        sys.exit(1)
